import threading
from tkinter import ttk, simpledialog  # 导入 simpledialog 用于创建输入对话框
import tkinter as tk
from tkinter import messagebox

from pk.WindowManager import WindowManager


class Baicaogu:
    def __init__(self, setupui):
        self.setupUi = setupui
        self.threads = []  # 用于存储所有挖图线程
        self.stop_flag = threading.Event()

    def btn_command(self):
        if any(thread.is_alive() for thread in self.threads):
            self.stop_flag.set()
            for thread in self.threads:
                thread.join(timeout=1)  # 增加超时时间
            self.threads = []  # 清空线程列表
            self.setupUi.btn_baicaogu.config(text="自动百草谷打怪")
            self.setupUi.add_log("停止自动百草谷打怪")
        else:
            if self.setupUi.selectHwnd:

                self.stop_flag.clear()
                # self.threads = []  # 清空线程列表
                for hwnd in self.setupUi.selectHwnd:
                    zhongzu = self.setupUi.handle_race_map.get(hwnd)
                    image_parth = None
                    if "人族" == zhongzu:
                        image_parth = "image/baicaogu/shifei.png"
                    elif "仙族" == zhongzu:
                        image_parth = "image/baicaogu/jiaoshui.png"
                    elif "魔族" == zhongzu:
                        image_parth = "image/baicaogu/zhuachong.png"
                    self.setupUi.add_log(f"开始自动百草谷打怪:{zhongzu}")
                    thread = threading.Thread(target=self.run_command, args=(hwnd, image_parth,))
                    thread.daemon = True
                    thread.start()
                    self.threads.append(thread)
                self.setupUi.btn_baicaogu.config(text="停止百草谷打怪")

            else:
                self.setupUi.add_log("未选择窗口，无法开始自动百草谷打怪")
                return

    def run_command(self, hwnd, image_parth):
        try:
            while True:
                if self.stop_flag.is_set():
                    break
                WindowManager.sleep(0.3)
                while not self.stop_flag.is_set():
                    WindowManager.sleep(0.1)
                    f = WindowManager.findImgAndClick(hwnd, image_parth)
                    if f:
                        break
                WindowManager.sleep(0.1)

        except Exception as e:
            print(f"百草谷打怪线程出错: {e}")
